package me.huha.zhime.service.impl;

import static me.huha.tools.Preconditions.check;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import me.huha.commons.Result;
import me.huha.ibatis.sqlbuilder.SpecificationBuilder;
import me.huha.tools.Invokers;
import me.huha.tools.Invokers.Invoker;
import me.huha.zhime.client.WeCharPayClientService;
import me.huha.zhime.commons.OrderInfoDTO;
import me.huha.zhime.entity.OrderInfoEntity;
import me.huha.zhime.entity.OrderInfoEntity.PaymentStatusEnum;
import me.huha.zhime.entity.OrderInfoEntity_;
import me.huha.zhime.pay.config.PayConfig;
import me.huha.zhime.pay.config.WeChatConfig;
import me.huha.zhime.pay.util.WeChatUtil;
import me.huha.zhime.service.OrderService;
import me.huha.zhime.utils.DoubleUtils;
import me.huha.zhime.utils.QRCodeUtil;
import me.huha.zhime.utils.Util;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.ModelAndView;

import com.google.gson.JsonObject;

/**
 * @Title: WeCharPayClientServiceImpl
 * @Author: Yepx
 * @mail: yepx2013@gmail.com
 * @CreateTime: 2017年10月25日 下午4:54:31
 * @Todo: TODO
 */
@Service("weCharPayClientService")
public class WeCharPayClientServiceImpl implements WeCharPayClientService {
	
	private static Logger logger = Logger.getLogger(WeCharPayClientServiceImpl.class);
	
	@Autowired
	private OrderService orderService;
	
	@Override
	public Result<Map<String, Object>> doPrepay(final OrderInfoDTO dto) {

		return Invokers.$(new Invoker<Map<String, Object>>() {
			@Override
			public Map<String, Object> apply() {
				
				String result = "";
				
				// 商户订单号，商户网站订单系统中唯一订单号，必填
				String orderNum = dto.getOrderNum();
				
				OrderInfoEntity entity = OrderInfoEntity.create(OrderInfoEntity.class)
														.findUnique(SpecificationBuilder.builder()
														.where(OrderInfoEntity_.orderNum.eq(orderNum)).build(), null);
				
				if(null != entity){
					Date orderClose = entity.getOrderClose();
					Date date = new Date();
					
					if(date.before(orderClose)){
						orderService.updateOrderPaymentStatus(orderNum, PaymentStatusEnum.unpaid);
					}else{
						orderService.updateOrderPaymentStatus(orderNum, PaymentStatusEnum.orderClose);
						check(true, "该订单已超时");
					}
				}else{
					orderService.createOrUpdateOrderInfo(dto);
				}
		        
				BigDecimal orderAmount = dto.getOrderAmount();
				// 付款金额，必填，单位分
				String total_amount = formatWecharTotalFee(orderAmount);
				// 订单名称，必填
				String subject = dto.getGoodName();
				
				// 终端IP,APP和网页支付提交用户端ip，Native支付填调用微信支付API的机器IP。
				String spbill_create_ip = dto.getWxPayIp();//"192.168.1.178";
				
				SortedMap<Object, Object> parameters = new TreeMap<Object, Object>();
				parameters.put("out_trade_no", orderNum);
				parameters.put("total_fee", total_amount);
				parameters.put("body", subject);
				parameters.put("detail", "");
				parameters.put("spbill_create_ip", spbill_create_ip);
				JsonObject jo = WeChatUtil.payPrepay(parameters);
				// createCode
				if ("SUCCESS".equals(jo.get("return_code").getAsString())
						&& "SUCCESS".equals(jo.get("result_code").getAsString())) {
					// 预支付成功
					result = QRCodeUtil.qRCodeImgAndUpload(jo.get("code_url").getAsString());
				} else {
					// 预支付失败
					check(true, "该订单预支付失败");
				}
				
				Map<String, Object> map = new HashMap<>();
				map.put("QRCodeUrl", result);
				map.put("WXpayUrl", jo.get("code_url").getAsString());
				return map;
			}
		});
	}
	
	
	/**
	 * 将金额转化为分
	 * @param orderAmount
	 * @return
	 */
	private static String formatWecharTotalFee(BigDecimal orderAmount){
		
		orderAmount = orderAmount.multiply(new BigDecimal(100));
		return orderAmount.intValue() + "";
	}
}
